import React, { Component } from 'react';
import { Card, Select, Table, Input, Button, Icon, message } from 'antd';
import { Modal } from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import LinkButton from '../../components/link-button';

const Option = Select.Option;
const { confirm } = Modal;

let sourceData = [{
    "_id": {
      "$oid": "5e12b97de31bb727e4b0e349"
    },
    "status": 2,
    "imgs": [
      "1578588737108-index.jpg"
    ],
    "name": "联想ThinkPad 翼4809",
    "desc": "年度重量级新品，X390、T490全新登场 更加轻薄机身设计9",
    "price": 6300,
    "pCategoryId": "5e12b8bce31bb727e4b0e348",
    "categoryId": "5fc74b650dd9b10798413162",
    "detail": "<p><span style=\"color: rgb(228,57,60);background-color: rgb(255,255,255);font-size: 12px;\">想你所需，超你所想！精致外观，轻薄便携带光驱，内置正版office杜绝盗版死机，全国联保两年！</span></p>\n<p><span style=\"color: rgb(102,102,102);background-color: rgb(255,255,255);font-size: 16px;\">联想（Lenovo）扬天V110 15.6英寸家用轻薄便携商务办公手提笔记本电脑 定制【E2-9010/4G/128G固态】 2G独显 内置</span></p>\n<p><span style=\"color: rgb(102,102,102);background-color: rgb(255,255,255);font-size: 16px;\"></span></p>\n",
    "__v": 0
  },{
    "_id": {
      "$oid": "5e12b9d1e31bb727e4b0e34a"
    },
    "status": 1,
    "imgs": [
      "image-1559402448049.jpg",
      "image-1559402450480.jpg"
    ],
    "name": "华硕(ASUS) 飞行堡垒",
    "desc": "15.6英寸窄边框游戏笔记本电脑(i7-8750H 8G 256GSSD+1T GTX1050Ti 4G IPS)",
    "price": 6799,
    "pCategoryId": "5e12b8bce31bb727e4b0e348",
    "categoryId": "5fc74b650dd9b10798413162",
    "detail": "<p><span style=\"color: rgb(102,102,102);background-color: rgb(255,255,255);font-size: 16px;\">华硕(ASUS) 飞行堡垒6 15.6英寸窄边框游戏笔记本电脑(i7-8750H 8G 256GSSD+1T GTX1050Ti 4G IPS)火陨红黑</span>&nbsp;</p>\n<p><span style=\"color: rgb(228,57,60);background-color: rgb(255,255,255);font-size: 12px;\">【4.6-4.7号华硕集体放价，大牌够品质！】1T+256G高速存储组合！超窄边框视野无阻，强劲散热一键启动！</span>&nbsp;</p>\n",
    "__v": 0
  },{
    "_id": {
      "$oid": "5e145c55d9ba8f39dc5f879f"
    },
    "status": 2,
    "imgs": [
      "image-1559402396338.jpg"
    ],
    "name": "联想ThinkPad 翼4809",
    "desc": "年度重量级新品，X390、T490全新登场 更加轻薄机身设计9",
    "price": "65999",
    "pCategoryId": "5e12b8bce31bb727e4b0e348",
    "categoryId": "5fc74b650dd9b10798413162",
    "__v": "0"
  },{
    "_id": {
      "$oid": "5e145c5ed9ba8f39dc5f87a1"
    },
    "status": "1",
    "imgs": [
      "image-1559402396338.jpg"
    ],
    "name": "联想ThinkPad 翼4809",
    "desc": "年度重量级新品，X390、T490全新登场 更加轻薄机身设计9",
    "price": "65999",
    "pCategoryId": "5e12b8bce31bb727e4b0e348",
    "categoryId": "5fc74b650dd9b10798413162",
    "__v": "0"
  },{
    "_id": {
      "$oid": "5e146b3cd9ba8f39dc5f87a2"
    },
    "status": "1",
    "imgs": [
      "image-1559402396338.jpg"
    ],
    "name": "联想ThinkPad 翼4809",
    "desc": "年度重量级新品，X390、T490全新登场 更加轻薄机身设计9",
    "price": "65999",
    "pCategoryId": "5e12b8bce31bb727e4b0e348",
    "categoryId": "5fc74b650dd9b10798413162",
    "detail": "",
    "__v": "0"
  },{
    "_id": {
      "$oid": "5e146b40d9ba8f39dc5f87a3"
    },
    "status": 2,
    "imgs": [
      "image-1559402396338.jpg"
    ],
    "name": "联想ThinkPad 翼4809",
    "desc": "年度重量级新品，X390、T490全新登场 更加轻薄机身设计9",
    "price": "65999",
    "pCategoryId": "5e12b8bce31bb727e4b0e348",
    "categoryId": "5fc74b650dd9b10798413162",
    "detail": "",
    "__v": "0"
  },{
    "_id": {
      "$oid": "5e146b44d9ba8f39dc5f87a4"
    },
    "status": "1",
    "imgs": [
      "image-1559402396338.jpg"
    ],
    "name": "联想ThinkPad 翼4809",
    "desc": "年度重量级新品，X390、T490全新登场 更加轻薄机身设计9",
    "price": "65999",
    "pCategoryId": "5e12b8bce31bb727e4b0e348",
    "categoryId": "5fc74b650dd9b10798413162",
    "detail": "",
    "__v": "0"
  },{
    "_id": {
      "$oid": "5e146b4dd9ba8f39dc5f87a5"
    },
    "status": 2,
    "imgs": [
      "image-1559402396338.jpg"
    ],
    "name": "联想ThinkPad 翼4809",
    "desc": "年度重量级新品，X390、T490全新登场 更加轻薄机身设计9",
    "price": "65999",
    "pCategoryId": "5e12b8bce31bb727e4b0e348",
    "categoryId": "5fc74b650dd9b10798413162",
    "detail": "",
    "__v": "0"
  },{
    "_id": {
      "$oid": "5e17045939c375286459fc82"
    },
    "imgs": [
      "image-1559402396338.jpg"
    ],
    "name": "测试一号",
    "desc": "哈哈哈哈哈哈",
    "price": 99999,
    "detail": "<p>少时诵诗书所所所</p>\n",
    "pCategoryId": "5e12b8bce31bb727e4b0e348",
    "categoryId": "5fc74b650dd9b10798413162",
    "status": 1,
    "__v": 0
  },{
    "_id": {
      "$oid": "5fc7096f0dd9b10798413160"
    },
    "status": 1,
    "imgs": [
      "image-1559402396338.jpg"
    ],
    "name": "美的(Midea) 213升-BCD-213TM",
    "desc": "爆款直降!大容量三口之家优选! *节能养鲜,自动低温补偿,36分贝静音呵护",
    "price": 1388,
    "pCategoryId": "5e12b8bce31bb727e4b0e348",
    "categoryId": "5fc30a1833fe4221c4546275",
    "detail": "<p style=\"text-align:start;\"><span style=\"color: rgb(102,102,102);background-color: rgb(255,255,255);font-size: 16px;font-family: Arial, \"microsoft yahei;\">美的(Midea) 213升 节能静音家用三门小冰箱 阳光米 BCD-213TM(E)</span></p>\n<p><span style=\"color: rgb(228,57,60);background-color: rgb(255,255,255);font-size: 12px;font-family: tahoma, arial, \"Microsoft YaHei\", \"Hiragino Sans GB\", u5b8bu4f53, sans-serif;\">【4.8美的大牌秒杀日】爆款直降!大容量三口之家优选! *节能养鲜,自动低温补偿,36分贝静音呵护! *每天不到一度电,省钱又省心!</span>&nbsp;</p>\n",
    "__v": 0
  },{
    "_id": {
      "$oid": "5fc709a00dd9b10798413161"
    },
    "status": 1,
    "imgs": [
      "image-1554638676149.jpg",
      "image-1554638683746.jpg"
    ],
    "name": "联想ThinkPad X1 Carbon",
    "desc": "英特尔酷睿i5 14英寸轻薄笔记本电脑（i5-8250U 8G 256GSSD FHD）黑色",
    "price": 9999,
    "pCategoryId": "5e12b8bce31bb727e4b0e348",
    "categoryId": "5fc74b650dd9b10798413162",
    "detail": "<p style=\"text-align:start;\"><span style=\"color: rgb(102,102,102);background-color: rgb(255,255,255);font-size: 16px;font-family: Arial, \"microsoft yahei;\">联想ThinkPad X1 Carbon 2018（09CD）英特尔酷睿i5 14英寸轻薄笔记本电脑（i5-8250U 8G 256GSSD FHD）黑色</span></p>\n<p><span style=\"color: rgb(228,57,60);background-color: rgb(255,255,255);font-size: 12px;font-family: tahoma, arial, \"Microsoft YaHei\", \"Hiragino Sans GB\", u5b8bu4f53, sans-serif;\">年度重量级新品，X390、T490全新登场 更加轻薄机身设计，全面的配置升级，让工作更便捷，让生活更轻松</span><a href=\"https://pro.jd.com/mall/active/2M4o7NTzHH6jEJXS7VbpbTAANQB9/index.html\" target=\"_blank\"><span style=\"color: rgb(94,105,173);background-color: rgb(255,255,255);font-size: 12px;font-family: tahoma, arial, \"Microsoft YaHei\", \"Hiragino Sans GB\", u5b8bu4f53, sans-serif;\">4月9日京东震撼首发，火爆预约</span></a>&nbsp;</p>\n",
    "__v": 0
  },{
    "_id": {
      "$oid": "5fc74fe10dd9b10798413163"
    },
    "status": 2,
    "imgs": [
      "image-1559402436395.jpg"
    ],
    "name": "你不知道的JS（上卷）",
    "desc": "图灵程序设计丛书： [You Don't Know JS:Scope & Closures] JavaScript开发经典入门图书 打通JavaScript的任督二脉",
    "price": 35,
    "pCategoryId": "0",
    "categoryId": "5e1346533ed02518b4db0cd7",
    "detail": "<p style=\"text-align:start;\"><span style=\"color: rgb(102,102,102);background-color: rgb(255,255,255);font-size: 16px;\">图灵程序设计丛书：你不知道的JavaScript（上卷）</span> <span style=\"color: rgb(102,102,102);background-color: rgb(255,255,255);font-size: 16px;\"><strong>[You Don't Know JS:Scope &amp; Closures]</strong></span></p>\n<p style=\"text-align:start;\"><span style=\"color: rgb(227,57,60);background-color: rgb(255,255,255);font-size: 12px;\">JavaScript开发经典入门图书 打通JavaScript的任督二脉 领略语言内部的绝美风光</span>&nbsp;</p>\n",
    "__v": 0
  },{
    "_id": {
      "$oid": "5fc9ea2b1cb7c416c4fb7edc"
    },
    "status": 1,
    "imgs": [],
    "categoryId": "5e12b8bce31bb727e4b0e348",
    "pCategoryId": "0",
    "name": "测试1",
    "price": 1000,
    "__v": 0
  },{
    "_id": {
      "$oid": "5fc9eca01cb7c416c4fb7ee1"
    },
    "status": 1,
    "imgs": [],
    "name": "123",
    "desc": "213",
    "price": 213,
    "pCategoryId": "0",
    "categoryId": "5e130e60e31bb727e4b0e34b",
    "__v": 0
  }].map(v => {
    return {
        ...v,
        '_id': v['_id']['$oid'],
        'imgs': [
          'https://gw.alipayobjects.com/zos/rmsportal/KDpgvguMpGfqaHPjicRK.svg',
          'https://gw.alipayobjects.com/zos/rmsportal/KDpgvguMpGfqaHPjicRK.svg',
          'https://gw.alipayobjects.com/zos/rmsportal/KDpgvguMpGfqaHPjicRK.svg'
        ]
    }
  });



class ProductHome extends Component {

    state = {
        loading: false,
        // 商品数组
        products: [],
        // 搜索关键字
        searchName: '',
        // 搜索类型
        searchType: 'productName'
    }
    
    /**
     * 初始化列
     */
    initColumns = () => {
        this.columns = [
            {
                title: '商品名称',
                width: 250,
                dataIndex: 'name',
            },
            {
                title: '商品描述',
                dataIndex: 'desc',
            },
            {
                title: '价格',
                width: 100,
                dataIndex: 'price',
                // 当前制定了对应的属性，传入的是对应的属性值
                render: (price) => '￥' + price
            },
            {
                title: '状态',
                width: 150,
                dataIndex: 'status',
                render: (status, row) => {
                   const { _id } = row;
                    return (
                        <span>
                            <span style={{ marginRight: '6px'}}>{status === 1 ? '在售' : '已下架'}</span>
                            <Button 
                            type="primary" 
                            onClick={() => this.updateStatus(_id, status === 1 ? 2 : 1)}
                            >
                              {status === 1 ? '下架' : '上架'}
                            </Button>
                        </span>
                    )
                }
            },
            {
                title: '操作',
                width: 150,
                render: (row) => {
                    return (
                        <span>
                          {/* 路由跳转传参，从this.props.location.state中取 */}
                          {/* this.props.history.push(path, state) */}
                            <LinkButton 
                            onClick={() => this.props.history.push('/product/detail', row)}
                            >详情</LinkButton>
                            <LinkButton 
                            onClick={() => this.props.history.push('/product/save', row)}
                            >修改</LinkButton>
                        </span>
                    )
                }
            }
        ];
    }

    
    /**
     * 获取商品列表数据
     */
    getProducts(){
        this.setState({
            loading: true,
            products: []
        });

        const { searchName, searchType } = this.state;
        setTimeout(() => {
            let productsFilter = [];
            // 这里先通过有无值来判断有点巧妙
            if(searchName){
                // 搜索
                // 真后台搜索这样更便捷
                // {
                //     pageNo,
                //     pageSize,
                //     [searchType]: searchName
                // }

                productsFilter = 
                searchType === 'productDesc' ? 
                // 判断一个字符串包含另一个字符串 str.search()
                sourceData.filter(v => v.desc && v.desc.search(searchName) !== -1) : 
                sourceData.filter(v => v.name && v.name.search(searchName) !== -1);

            }else{
                productsFilter = [...sourceData];
            }
            this.setState({
                products: productsFilter,
                loading: false
            });
        }, 1000);
    }

    
    /**
     * 搜索重置
     */
    searchReset(){
        this.setState({
            searchType: 'productName',
            searchName: ''
        },() => {
            this.getProducts();
        });
    }

    
    /**
     * 修改商品状态
     */
    updateStatus(id, newStatus){
      console.log(id, newStatus);
      // 显示确认框
      confirm({
          title: `确定${newStatus === 1 ? '下架' : '上架' }吗？`,
          icon: <ExclamationCircleOutlined />,
          onOk: () => {
            sourceData.forEach(v => {
              if(v['_id'] === id){
                message.success('更新成功');
                v.status = newStatus;
                this.getProducts();
              }
            }); 
          }
      });
    }


    UNSAFE_componentWillMount(){
        this.initColumns();
    }

    componentDidMount(){
        this.getProducts(); 
    }

    render() {

        const { loading, products, searchName, searchType } = this.state;

        const title = (
            <span>
                <Select 
                value={searchType} 
                style={{ width: 150 }} 
                onChange={value => this.setState({searchType: value})}
                >
                    <Option value="productName">按名称搜索</Option>
                    <Option value="productDesc">按描述搜索</Option>
                </Select>
                <Input 
                value={searchName} 
                placeholder='关键字' 
                style={{ width: 180, margin: '0 5px' }} 
                onChange={event => this.setState({searchName: event.target.value})}
                />
                <Button type="primary" onClick={() => this.getProducts()} style={{ marginRight: '5px' }} >搜索</Button>
                <Button onClick={() => {this.search()}}>重置</Button>
            </span>
        );

        const extra = (
            <Button type="primary" onClick={() => this.props.history.push('/product/save')}>
                <Icon type="plus" />
                添加商品
            </Button>
        );

        return (
            <Card title={title} extra={extra}>
                <Table 
                loading={loading}
                bordered
                rowKey='_id'
                dataSource={products} 
                columns={this.columns} 
                pagination={{ defaultPageSize: 5, showQuickJumper: true }}
                />
            </Card>
        );
    }
}

export default ProductHome;